#!BPY
# encoding: utf-8

"""
Name: 'ANZ Material IPO Generator'
Blender: 249
Group: 'Animation'
Tooltip: 'Generates IPO curves for material animation'
"""

__author__ = 'Desuwa'
__version__ = '0.2'
__url__ = "http://code.google.com/p/anz2blend/"
__email__ = "desuwane@gmail.com"

"""
The MIT License

Copyright (c) 2011 Desuwa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import Blender
from Blender import Ipo, IpoCurve, Material, BGL
from Blender.BGL import *
import bpy

#----------------
# GUI
#----------------
ROWS = Blender.Draw.Create(2)
COLS = Blender.Draw.Create(2)
FRAMES = Blender.Draw.Create(1)
DELAY = Blender.Draw.Create(1)
LOOPS = Blender.Draw.Create(1)
LOOPBACK = Blender.Draw.Create(0)

def guiEvent(event, value):	
	if event == Blender.Draw.ESCKEY:
		Blender.Draw.Exit()
		return

def guiButton(event):
	if event == 666:
		generateIpos()
		Blender.Draw.Exit()
	elif event == 999:
		Blender.Draw.Exit()
	
	Blender.Draw.Redraw(1)

def drawGui():
	global ROWS, COLS, FRAMES, DELAY, LOOPS, LOOPBACK
	
	glClearColor(0.55, 0.57, 0.67, 1)
	glClear(BGL.GL_COLOR_BUFFER_BIT)
	
	glColor3f(0.70, 0.71, 0.85)
	glRasterPos2i(35, 40)
	Blender.Draw.Text("KISS ANZ Material IPO Generator " + __version__, "large")
	glRasterPos2i(35, 25)
	Blender.Draw.Text(__url__, "small")
	
	yD = 90
	
	glColor3f(0.16, 0.168, 0.2)
	
	COLS = Blender.Draw.Number("Columns:",
		1, 35, 160 + yD, 150, 18, COLS.val, 2, 100)
	glRasterPos2i(195, 165 + yD)
	Blender.Draw.Text("Number of columns")
	
	ROWS = Blender.Draw.Number("Rows:",
		2, 35, 135 + yD, 150, 18, ROWS.val, 2, 100)
	glRasterPos2i(195, 140 + yD)
	Blender.Draw.Text("Number of rows")

	FRAMES = Blender.Draw.Number("Frames:",
		3, 35, 110 + yD, 150, 18, FRAMES.val, 1, 100)
	glRasterPos2i(195, 115 + yD)
	Blender.Draw.Text("Number of tiles in the texture")
	
	LOOPS = Blender.Draw.Number("Loops:",
		4, 35, 85 + yD, 150, 18, LOOPS.val, 1, 100)
	glRasterPos2i(195, 90 + yD)
	Blender.Draw.Text("Number of loops")
	
	DELAY = Blender.Draw.Number("Delay:",
		5, 35, 60 + yD, 150, 18, DELAY.val, 1, 100)
	glRasterPos2i(195, 65 + yD)
	Blender.Draw.Text("Number of frames between each keyframe")
	
	LOOPBACK = Blender.Draw.Toggle("Loop Back",
		6, 35, 35 + yD, 150, 18, LOOPBACK.val)
	glRasterPos2i(195, 40 + yD)
	Blender.Draw.Text("Animate backwards at the end")
	
	Blender.Draw.PushButton("Generate", 666, 35, 70, 75, 30, "")
	Blender.Draw.PushButton("Cancel", 999, 120, 70, 75, 30, "")
	
#----------------
# Main
#----------------
def generateIpos():
	global COLS, ROWS, FRAMES, DELAY, LOOPS, LOOPBACK
	
	COLS = COLS.val
	ROWS = ROWS.val
	FRAMES = FRAMES.val
	DELAY = DELAY.val
	LOOPS = LOOPS.val
	LOOPBACK = LOOPBACK.val
	
	if FRAMES > COLS * ROWS:
		print "Invalid frame count (Frames > Columns * Rows). Aborting."
		return
	
	stepX = 1.0 / COLS
	stepY = 1.0 / ROWS
	endFrame = FRAMES * DELAY * LOOPS + 1
	
	scn = bpy.data.scenes.active
	mesh = scn.objects.active.getData(mesh = True)
	mat = mesh.materials[0]
	
	print "Generating curves for %s" % mat.name
	
	ipo = Ipo.New("Material", "TexAnim")
	ofsx = ipo.addCurve("OfsX")
	ofsy = ipo.addCurve("OfsY")
	ofsx.interpolation = IpoCurve.InterpTypes.CONST
	ofsy.interpolation = IpoCurve.InterpTypes.CONST
	
	mat.setIpo(ipo)
	
	mTex = mat.getTextures()[0]
	
	curframe = 1
	for loop in xrange(0, LOOPS):
		for row in xrange(0, ROWS):
			y = -stepY * row
			for col in xrange(0, COLS):
				Blender.Set('curframe', curframe)
				if curframe >= endFrame: break
				mTex.ofs = (stepX * col, y, 0)
				mat.insertIpoKey(Material.OFS)
				curframe += DELAY
	
	if LOOPBACK:
		loopEnd = endFrame * 2 - DELAY
		curframe -= DELAY
		for row in xrange(ROWS - 1, -1, -1):
			y = -stepY * row
			for col in xrange(COLS - 1, -1, -1):
				Blender.Set('curframe', curframe)
				if curframe >= loopEnd: break
				mTex.ofs = (stepX * col, y, 0)
				mat.insertIpoKey(Material.OFS)
				curframe += DELAY
		curframe -= DELAY
	
	Blender.Set('curframe', 1)
	scn.getRenderingContext().endFrame(curframe)

#----------------
# Here it comes
#----------------
sel = bpy.data.scenes.active.objects.active
if sel is None:
	print "No active object. Aborting."
elif sel.getType() != "Mesh":
	print "Active object is not a Mesh. Aborting."
else:
	Blender.Draw.Register(drawGui, guiEvent, guiButton)
